package com.example.mymusic;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import java.util.ArrayList;
import androidx.annotation.RequiresApi;

/**
 * @author xky
 */
public class MusicWidget extends AppWidgetProvider {
    private ArrayList<Music> listMusic;
    private Music music;
    private SQLiteOpenHelper helper;



    private int position;
    private final String tag = "MusicWidget";
    public static final int WIDGET_SERVICE_PLAY_PAUSE = 1;
    int positionOriginal;
    int stateOriginal;
    int activityOriginal;

    public int queryPosition(Context context){
        helper = new MySqLiteOpenHelper(context, "media_player_data.db", null, 1);
        SQLiteDatabase sqliteDatabase = helper.getReadableDatabase();
        //position_data 建表时 = -1
        @SuppressLint("Recycle")
        Cursor cursor = sqliteDatabase.query("media_player_table", new String[]{"id", "position_data"}, "id=?", new String[]{"1"}, null, null, null);
        int positionOriginalMethod = 0;
        while (cursor.moveToNext()) {
            positionOriginalMethod = cursor.getInt(cursor.getColumnIndex("position_data"));
        }
        return positionOriginalMethod;
    }

    public int queryActivity(Context context){
        helper = new MySqLiteOpenHelper(context, "media_player_data.db", null, 1);
        SQLiteDatabase sqliteDatabase = helper.getReadableDatabase();
        //position_data 建表时 = -1
        @SuppressLint("Recycle")
        Cursor cursor = sqliteDatabase.query("media_player_table", new String[]{"id", "main_activity_data"}, "id=?", new String[]{"1"}, null, null, null);
        int activityOriginalMethod = 0;
        while (cursor.moveToNext()) {
            activityOriginalMethod = cursor.getInt(cursor.getColumnIndex("main_activity_data"));
        }
        return activityOriginalMethod;
    }

    public int queryState(Context context){
        helper = new MySqLiteOpenHelper(context, "media_player_data.db", null, 1);
        SQLiteDatabase sqliteDatabase = helper.getReadableDatabase();
        //player_state_data 建表时 = 0
        @SuppressLint("Recycle")
        Cursor cursor = sqliteDatabase.query("media_player_table", new String[]{"id","player_state_data"}, "id=?", new String[]{"1"}, null, null, null);
        int stateOriginalMethod = 0;
        while (cursor.moveToNext()) {
            stateOriginalMethod = cursor.getInt(cursor.getColumnIndex("player_state_data"));
        }
        return stateOriginalMethod;
    }


    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onEnabled(Context context) {
        Log.i(tag, "onEnabled: ");
        helper = new MySqLiteOpenHelper(context, "media_player_data.db", null, 1);
        helper.getWritableDatabase();

        positionOriginal = queryPosition(context);
        Log.e("微件创建时查询出来数据:", "position_original: "+ positionOriginal);

        if (positionOriginal == -1 ) {
            //服务未启动
            Log.i(tag, "onEnabled: new");
            listMusic = Utils.getMusic(context);
            position = 0;

            positionOriginal = queryPosition(context);
            if (positionOriginal != -1 ) {
                position = positionOriginal;
            }

            Bundle bundle = new Bundle();
            listMusic = Utils.getMusic(context);
            bundle.putInt("position", position);
            Intent intent = new Intent();
            intent.putExtras(bundle);
            intent.setClass(context, MusicService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }

        } else {
            Log.i(tag, "onEnabled: ");
            //服务启动了就获取当前歌曲
            positionOriginal = queryPosition(context);
            position = positionOriginal;
            listMusic = Utils.getMusic(context);
            music = listMusic.get(position);

        }

        updateUI(context, AppWidgetManager.getInstance(context));
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        onEnabled(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onReceive(Context context, Intent intent) {
        positionOriginal = queryPosition(context);
        listMusic = Utils.getMusic(context);
        position = positionOriginal;

        String action = intent.getAction();
        //接受update意图的广播就更新
        String update = "update";
        if (update.equals(action)) {
            Log.i(tag, "onReceive: update");
            updateUI(context, AppWidgetManager.getInstance(context));
        }

        super.onReceive(context, intent);
    }


    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void updateUI(Context context, AppWidgetManager appWidgetManager) {
        RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
        Log.i(tag, "updateUI: " + position);
        listMusic = Utils.getMusic(context);
        music = listMusic.get(position);


        remoteView.setTextViewText(R.id.music_name, music.name);
        Bitmap bitmap;
        byte[] cover = Utils.getCover(music.path);
        if (cover != null) {
            bitmap = BitmapFactory.decodeByteArray(cover, 0, cover.length);
            remoteView.setImageViewBitmap(R.id.background, bitmap);
        }else {
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.yuantu2);
        }
        remoteView.setImageViewBitmap(R.id.background, bitmap);

        int widgetMusicActivity = 12;


        activityOriginal = queryActivity(context);
        if (activityOriginal==1){
            remoteView.setOnClickPendingIntent(R.id.music_name, getPendingIntent(context, widgetMusicActivity));
        }

        //RemoteViews创建SetOnClickPendingIntent并把id和intent传入，SetOnClickPendingIntent保存这些值

        int playPause = 3;
        remoteView.setOnClickPendingIntent(R.id.play_pause, getPendingIntent(context, playPause, "play"));
        int preMusic = 4;
        remoteView.setOnClickPendingIntent(R.id.pre_music, getPendingIntent(context, preMusic, "pre"));
        int nextMusic = 5;
        remoteView.setOnClickPendingIntent(R.id.next_music, getPendingIntent(context, nextMusic, "next"));

        stateOriginal = queryState(context);
        if (stateOriginal==1) {
            remoteView.setImageViewResource(R.id.play_pause, R.mipmap.pause);
        } else {
            remoteView.setImageViewResource(R.id.play_pause, R.mipmap.play);
        }
        ComponentName componentName = new ComponentName(context, MusicWidget.class);
        appWidgetManager.updateAppWidget(componentName, remoteView);
    }

    /**
     * 点击跳转activity
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private PendingIntent getPendingIntent(Context context, int requestCode) {
        Bundle bundle = new Bundle();
        listMusic = Utils.getMusic(context);
        bundle.putInt("position", position);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClass(context, MusicActivity.class);
        return PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    /**
     * 实现按钮功能,把按钮操作后的position发送去service，并且启动服务
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private PendingIntent getPendingIntent(Context context, int requestCode, String button) {
        Intent intent = new Intent(context, MusicService.class);
        Bundle bundle = new Bundle();
        listMusic = Utils.getMusic(context);

        int widgetPosition = position;
        switch (button) {
            case "pre":
                widgetPosition = (position - 1 + listMusic.size()) % listMusic.size();
                break;
            case "next":
                widgetPosition = (position + 1 + listMusic.size()) % listMusic.size();
                break;
            case "play":
                bundle.putInt("action", WIDGET_SERVICE_PLAY_PAUSE);
                break;
            default:
                break;
        }

        bundle.putInt("position", widgetPosition);
        intent.putExtras(bundle);
        return PendingIntent.getService(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {

        super.onDeleted(context, appWidgetIds);
        // Widget从屏幕移除
        stateOriginal = queryState(context);
        if (stateOriginal==0){
            Log.e("Widget::onDeleted:", "恢复数据库原样");
            helper = new MySqLiteOpenHelper(context, "media_player_data.db", null, 1);
            SQLiteDatabase sqliteDatabase = helper.getWritableDatabase();
            sqliteDatabase.execSQL("update media_player_table set position_data=-1 where id=1");
            sqliteDatabase.execSQL("update media_player_table set player_state_data=0 where id=1");
        }



    }
}
